package com.sun.personal.service.impl;

import com.sun.bean.SysUser;
import com.sun.personal.mapper.SysUserMapper;
import com.sun.personal.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author syh
 * @date 2021/7/3 11:55
 */
@Service
public class SysUserServiceImpl implements SysUserService, UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<SysUser> findSysUserAll() {
        return sysUserMapper.selectAllUser();
    }

    @Override
    public SysUser findSysUserByName(String username) {
        return sysUserMapper.findSysUserByName(username);
    }

    /**
     * 查询数据库完成认证
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user = sysUserMapper.findSysUserByName(s);
        List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("role");

        /**
         * 查询出来的是明文的用户名和加密的密码
         * 如果数数据库存储的是密文： 直接写即可：return new User(user.getUserName(),user.getPassword(),authorityList);
         * 如果说数据库存储的是明文： 需要先加密：return new User(user.getUserName(),new BCryptPasswordEncoder().encode(user.getPassword()),authorityList);
         */
        //return new User(user.getUserName(),new BCryptPasswordEncoder().encode(user.getPassword()),authorityList);
        return new User(user.getUserName(),user.getPassword(),authorityList);

    }

}

